package com.xhy.documents_collection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.entity.PO.task.Task;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.entity.PO.team.TeamUser;
import com.xhy.documents_collection.entity.PO.team.UserRole;
import com.xhy.documents_collection.mapper.UserMapper;
import com.xhy.documents_collection.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhy.documents_collection.service.authority.UserRoleService;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.xhy.documents_collection.service.task.TaskService;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.service.team.TeamUserService;
import com.xhy.documents_collection.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-11-14
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleService userRoleService;

    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public User getUserByStudentNumber(String studentNumber) {
        return userMapper.getUserByStudentNumber(studentNumber);
    }

    @Override
    @Transactional
    public R addUser(User user) {
        Integer count = baseMapper.selectCount(new QueryWrapper<User>().eq("email", user.getEmail()).or().eq("student_number",user.getStudentNumber()));

        if (count >= 1){
            return R.error().message("已被注册");
        }


        baseMapper.insert(user);

        UserRole userRole = new UserRole();
        userRole.setUId(user.getId());
        userRole.setRId(14);
        userRoleService.save(userRole);

        return R.ok().message("添加成功");
    }

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private TeamService teamService;

    @Resource
    private TaskService taskService;

    @Resource
    private TaskRecordService taskRecordService;

    @Override
    @Transactional
    public R removeUsers(String ids) {
        List<String> userIds = null;
        Integer uId = UserHolder.get();
        try{
            // 取出所有用户id
            userIds = Arrays.asList(ids.split(","));

            // 删除用户
            baseMapper.deleteBatchIds(userIds);

            // 删除用户角色中间表数据
            userRoleService.remove(new QueryWrapper<UserRole>().in("u_id",userIds));

            // 删除团队角色表中的该角色
            teamUserService.remove(new QueryWrapper<TeamUser>().in("u_id",userIds));

            // 删除用户所拥有的团队
                // 1.查出所有团队
            List<Integer> teamIds = teamService.list(new QueryWrapper<Team>().eq("u_id", uId).select("id")).stream().map(Team::getId).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(teamIds)){
                // 删除用户团队下创建的任务
                    // 2.根据团队查出所有任务
                List<Integer> taskIds = taskService.list(new QueryWrapper<Task>().in("t_id", teamIds).select("id")).stream().map(Task::getId).collect(Collectors.toList());
                if (!ObjectUtils.isEmpty(taskIds)){
                    // 删除用户团队创建任务下的任务记录
                    // 3.根据任务查出任务下的记录
                    taskRecordService.remove(new QueryWrapper<TaskRecord>().in("t_id",taskIds));
                    taskService.removeByIds(taskIds);
                }
                teamService.removeByIds(teamIds);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            return R.error().message("删除用户异常");
        }
        return R.ok().message("删除成功");
    }

    @Override
    public R updateUser(User user) {
        Integer userId = user.getId();
        User u = getById(userId);
        if (ObjectUtils.isEmpty(u)){
            return R.error().message("用户不存在");
        }
        user.setId(userId);
        updateById(user);
        return R.ok().message("修改成功");
    }


}
